<template>
  <div class="home" style="padding: 10px">
    <!-- 搜索 -->
    <div style="margin: 10px 0;">
      <el-form inline size="small">
        <el-form-item label="图书编号">
          <el-input v-model="search1" placeholder="请输入图书编号" clearable>
            <template #prefix>
              <el-icon class="el-input__icon"><search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="图书名称">
          <el-input v-model="search2" placeholder="请输入图书名称" clearable>
            <template #prefix>
              <el-icon class="el-input__icon"><search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="作者">
          <el-input v-model="search3" placeholder="请输入作者" clearable>
            <template #prefix>
              <el-icon class="el-input__icon"><search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" style="margin-left: 1%" @click="load" size="mini">
            <svg-icon iconClass="search" /> 查询
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button size="mini" type="danger" @click="clear">重置</el-button>
        </el-form-item>
        <el-form-item style="float: right" v-if="numOfOutDataBook">
          <el-popconfirm
              confirm-button-text="查看"
              cancel-button-text="取消"
              :icon="InfoFilled"
              icon-color="red"
              title="您有图书已逾期，请尽快归还"
              @confirm="toLook"
          >
            <template #reference>
              <el-button type="warning">逾期通知</el-button>
            </template>
          </el-popconfirm>
        </el-form-item>
      </el-form>
    </div>

    <!-- 按钮 -->
    <div style="margin: 10px 0;">
      <el-button type="primary" @click="add" v-if="user.role === 1">上架</el-button>
      <el-popconfirm title="确认删除?" @confirm="deleteBatch" v-if="user.role === 1">
        <template #reference>
          <el-button type="danger" size="mini">批量删除</el-button>
        </template>
      </el-popconfirm>
    </div>

    <!-- 表格 -->
    <el-table :data="tableData" stripe border @selection-change="handleSelectionChange">
      <el-table-column v-if="user.role === 1" type="selection" width="55" />
      <el-table-column prop="isbn" label="图书编号" sortable />
      <el-table-column prop="name" label="图书名称" />
      <el-table-column prop="price" label="价格" sortable />
      <el-table-column prop="author" label="作者" />
      <el-table-column prop="publisher" label="出版社" />
      <el-table-column prop="createTime" label="出版时间" sortable />
      <el-table-column prop="status" label="状态">
        <template #default="{ row }">
          <!-- 修复：使用双等号或转换类型进行比较 -->
          <el-tag v-if="row.status == 0 || row.status === '0'" type="warning">已借阅</el-tag>
          <el-tag v-else type="success">未借阅</el-tag>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作">
        <template #default="{ row }">
          <el-button v-if="user.role === 1" size="mini" @click="handleEdit(row)">修改</el-button>
          <el-popconfirm
              v-if="user.role === 1"
              title="确认删除?"
              @confirm="() => handleDelete(row.id)"
          >
            <template #reference>
              <el-button type="danger" size="mini">删除</el-button>
            </template>
          </el-popconfirm>

          <el-button
              v-if="user.role === 2"
              size="mini"
              @click="() => handleLend(row.id, row.isbn, row.name, row.borrownum)"
              :disabled="row.status === 0"
          >借阅</el-button>

          <el-popconfirm
              v-if="user.role === 2"
              title="确认还书?"
              @confirm="() => handleReturn(row.id, row.isbn, row.name, row.borrownum)"
          >
            <template #reference>
              <el-button
                  type="danger"
                  size="mini"
                  :disabled="!isbnArray.includes(row.isbn) || row.status === 1"
              >还书</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 逾期详情对话框 -->
    <el-dialog
        v-model="dialogVisible3"
        v-if="numOfOutDataBook"
        title="逾期详情"
        width="50%"
        :before-close="handleClose"
    >
      <el-table :data="outDateBook" style="width: 100%">
        <el-table-column prop="isbn" label="图书编号" />
        <el-table-column prop="bookName" label="书名" />
        <el-table-column prop="lendtime" label="借阅日期" />
        <el-table-column prop="deadtime" label="截至日期" />
      </el-table>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="dialogVisible3 = false">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分页 -->
    <div style="margin: 10px 0">
      <el-pagination
          v-model:current-page="currentPage"
          :page-sizes="[5, 10, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />

      <!-- 上架书籍 -->
      <el-dialog v-model="dialogVisible" title="上架书籍" width="30%">
        <el-form :model="form" label-width="120px">
          <el-form-item label="图书编号">
            <el-input v-model="form.isbn" style="width: 80%" />
          </el-form-item>
          <el-form-item label="图书名称">
            <el-input v-model="form.name" style="width: 80%" />
          </el-form-item>
          <el-form-item label="价格">
            <el-input v-model="form.price" style="width: 80%" />
          </el-form-item>
          <el-form-item label="作者">
            <el-input v-model="form.author" style="width: 80%" />
          </el-form-item>
          <el-form-item label="出版社">
            <el-input v-model="form.publisher" style="width: 80%" />
          </el-form-item>
          <el-form-item label="出版时间">
            <el-date-picker
                v-model="form.createTime"
                value-format="YYYY-MM-DD"
                type="date"
                clearable
                style="width: 80%"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="save">确定</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 修改书籍信息 -->
      <el-dialog v-model="dialogVisible2" title="修改书籍信息" width="30%">
        <el-form :model="form" label-width="120px">
          <el-form-item label="图书编号">
            <el-input v-model="form.isbn" style="width: 80%" />
          </el-form-item>
          <el-form-item label="图书名称">
            <el-input v-model="form.name" style="width: 80%" />
          </el-form-item>
          <el-form-item label="价格">
            <el-input v-model="form.price" style="width: 80%" />
          </el-form-item>
          <el-form-item label="作者">
            <el-input v-model="form.author" style="width: 80%" />
          </el-form-item>
          <el-form-item label="出版社">
            <el-input v-model="form.publisher" style="width: 80%" />
          </el-form-item>
          <el-form-item label="出版时间">
            <el-date-picker
                v-model="form.createTime"
                value-format="YYYY-MM-DD"
                type="date"
                clearable
                style="width: 80%"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible2 = false">取消</el-button>
            <el-button type="primary" @click="save">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import request from "../utils/request";
import { ElMessage } from "element-plus";
import moment from "moment";
import { Search, InfoFilled } from "@element-plus/icons-vue";

export default {
  name: "BookManager",
  components: {
    Search,
    InfoFilled,
  },
  data() {
    return {
      form: {},
      dialogVisible: false,
      dialogVisible2: false,
      dialogVisible3: false,
      search1: "",
      search2: "",
      search3: "",
      total: 0,
      currentPage: 1,
      pageSize: 10,
      tableData: [],
      user: {},
      number: 0,
      bookData: [],
      isbnArray: [],
      outDateBook: [],
      numOfOutDataBook: 0,
    };
  },
  created() {
    const userStr = sessionStorage.getItem("user") || "{}";
    this.user = JSON.parse(userStr);
    this.load();
  },
  methods: {
    load() {
      this.numOfOutDataBook = 0;
      this.outDateBook = [];
      // 加载图书列表
      request
          .get("/book", {
            params: {
              pageNum: this.currentPage,
              pageSize: this.pageSize,
              search1: this.search1,
              search2: this.search2,
              search3: this.search3,
            },
          })
          .then((res) => {
            this.tableData = res.data.records;
            this.total = res.data.total;
          })
          .catch((err) => {
            console.error(err);
            ElMessage.error(`加载失败: ${err.response?.status}`);
          });

      // 如果是读者，加载借阅记录检测逾期
      if (this.user.role === 2) {
        request
            .get("/bookwithuser", {
              params: {
                pageNum: 1,
                pageSize: this.total || 1000,
                search3: this.user.id,
              },
            })
            .then((res) => {
              this.bookData = res.data.records;
              this.number = this.bookData.length;
              const now = new Date();
              this.bookData.forEach((item) => {
                this.isbnArray.push(item.isbn);
                const dead = new Date(item.deadtime);
                if (dead < now) {
                  this.outDateBook.push({
                    isbn: item.isbn,
                    bookName: item.bookName,
                    lendtime: item.lendtime,
                    deadtime: item.deadtime,
                  });
                  this.numOfOutDataBook++;
                }
              });
            })
            .catch((err) => {
              console.error(err);
              ElMessage.error(`借阅记录加载失败: ${err.response?.status}`);
            });
      }
    },

    clear() {
      this.search1 = "";
      this.search2 = "";
      this.search3 = "";
      this.load();
    },

    handleSelectionChange(val) {
      this.ids = val.map((v) => v.id);
    },

    deleteBatch() {
      if (!this.ids || !this.ids.length) {
        return ElMessage.warning("请选择要删除的图书");
      }
      request
          .post("/book/deleteBatch", this.ids)
          .then(() => {
            ElMessage.success("批量删除成功");
            this.load();
          })
          .catch((err) => {
            console.error(err);
            ElMessage.error(`删除失败: ${err.response?.status}`);
          });
    },

    handleDelete(id) {
      request
          .delete(`/book/${id}`)
          .then(() => {
            ElMessage.success("删除成功");
            this.load();
          })
          .catch((err) => {
            console.error(err);
            ElMessage.error(`删除失败: ${err.response?.status}`);
          });
    },

    handleEdit(row) {
      this.form = { ...row };
      this.dialogVisible2 = true;
    },

    save() {
      if (this.form.id) {
        // 修改
        request
            .put("/book", this.form)
            .then(() => {
              ElMessage.success("修改成功");
              this.load();
              this.dialogVisible2 = false;
            })
            .catch((err) => {
              console.error(err);
              ElMessage.error(`修改失败: ${err.response?.status}`);
            });
      } else {
        // 新增
        this.form.borrownum = 0;
        this.form.status = 1;
        request
            .post("/book", this.form)
            .then(() => {
              ElMessage.success("上架成功");
              this.load();
              this.dialogVisible = false;
            })
            .catch((err) => {
              console.error(err);
              ElMessage.error(`上架失败: ${err.response?.status}`);
            });
      }
    },

    // 修复后的 handleLend 方法
    async handleLend(id, isbn, name, bn) {
      if (this.number >= 5) {
        return ElMessage.warning("最多可借 5 本书");
      }
      if (this.numOfOutDataBook > 0) {
        return ElMessage.warning("请先归还逾期图书");
      }

      try {
        const currentTime = moment().format("YYYY-MM-DD HH:mm:ss");

        // 第一步：更新图书状态
        const upd = { id, status: 0, borrownum: bn + 1 };
        await request.put("/book", upd);
        ElMessage.success("借阅：图书状态更新成功");

        // 第二步：新增借阅记录
        const rec = {
          isbn,
          bookname: name,
          readerId: this.user.id,
          borrownum: bn + 1,
          lendTime: currentTime,
          returnTime: "9999-12-31 23:59:59", // 使用占位时间
          status: 0, // 0表示未归还
        };

        await request.post("/lendRecord", rec);
        ElMessage.success("借阅：记录插入成功");

        // 第三步：新增关联展示
        const disp = {
          isbn,
          bookName: name,
          nickName: this.user.username,
          id: this.user.id,
          lendtime: currentTime,
          deadtime: moment().add(30, "days").format("YYYY-MM-DD HH:mm:ss"),
          prolong: 1,
        };

        await request.post("/bookwithuser/insertNew", disp);
        ElMessage.success("借阅：展示关联插入成功");

        // 所有操作完成后刷新页面数据
        ElMessage.success("借阅成功！");
        this.load();

      } catch (err) {
        console.error("借阅操作失败:", err);
        ElMessage.error(`借阅失败: ${err.response?.data?.msg || err.message}`);
        // 发生错误时也要刷新数据，确保页面显示最新状态
        this.load();
      }
    },

// 修复后的 handleReturn 方法
    async handleReturn(id, isbn, name, bn) {
      try {
        const currentTime = moment().format("YYYY-MM-DD HH:mm:ss");

        // 第一步：更新图书状态
        const upd = { id, status: 1 };
        await request.put("/book", upd);
        ElMessage.success("还书：图书状态更新成功");

        // 第二步：更新借阅记录
        const recUpd = {
          isbn,
          readerId: this.user.id,
          returnTime: currentTime,
          status: 1,
        };
        await request.put("/lendRecord1", recUpd);
        ElMessage.success("还书：借阅记录更新成功");

        // 第三步：删除展示关联
        const delDisp = {
          isbn,
          bookName: name,
          nickName: this.user.username,
          id: this.user.id,
          lendtime: currentTime,
          deadtime: currentTime,
          prolong: 1,
        };
        await request.post("/bookwithuser/deleteRecord", delDisp);
        ElMessage.success("还书：展示关联删除成功");

        // 重要：立即更新前端状态数据
        // 从 isbnArray 中移除已还书的 isbn
        const isbnIndex = this.isbnArray.indexOf(isbn);
        if (isbnIndex > -1) {
          this.isbnArray.splice(isbnIndex, 1);
        }

        // 更新借阅数量
        this.number = Math.max(0, this.number - 1);

        // 立即更新当前行的状态，避免等待重新加载
        const currentRow = this.tableData.find(item => item.id === id);
        if (currentRow) {
          currentRow.status = 1; // 更新为未借阅状态
        }

        // 所有操作完成后刷新页面数据（确保数据同步）
        ElMessage.success("还书成功！");
        this.load();

      } catch (err) {
        console.error("还书操作失败:", err);
        ElMessage.error(`还书失败: ${err.response?.data?.msg || err.message}`);
        // 发生错误时也要刷新数据，确保页面显示最新状态
        this.load();
      }
    },
    toLook() {
      this.dialogVisible3 = true;
    },

    handleClose() {
      this.dialogVisible3 = false;
    },

    handleSizeChange(size) {
      this.pageSize = size;
      this.currentPage = 1;
      this.load();
    },

    handleCurrentChange(page) {
      this.currentPage = page;
      this.load();
    },
  },
};
</script>

<style scoped>
.home {
  padding: 10px;
}
</style>
